package com.retail.admin.service.impl;

import com.retail.admin.dto.LoginRequest;
import com.retail.admin.dto.LoginResponse;
import com.retail.admin.dto.UserInfo;
import com.retail.admin.service.AuthService;
import com.retail.common.utils.JwtUtils;
import com.retail.user.entity.User;
import com.retail.user.service.UserService;
import com.retail.user.dto.UserVO;
import com.retail.user.dto.RoleVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 认证服务实现类
 * 基于数据库的用户认证和权限验证
 *
 * @author retail
 * @since 2024-01-01
 */
@Service
public class AuthServiceImpl implements AuthService {

    private static final Logger log = LoggerFactory.getLogger(AuthServiceImpl.class);

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserService userService;

    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        log.info("用户登录请求，用户名：{}", loginRequest.getUsername());

        // 从数据库查询用户
        User user = userService.getUserByUsername(loginRequest.getUsername());
        if (user == null) {
            log.warn("用户不存在，用户名：{}", loginRequest.getUsername());
            throw new RuntimeException("用户名或密码错误");
        }

        // 验证密码（暂时使用明文比对）
        log.info("存储的密码: {}", user.getPassword());
        log.info("输入的密码: {}", loginRequest.getPassword());
       
        if (!loginRequest.getPassword().equals(user.getPassword())) {
            log.warn("密码错误，用户名：{}", loginRequest.getUsername());
            throw new RuntimeException("用户名或密码错误");
        }

        // 获取用户详细信息（包含角色信息）
        UserVO userVO = userService.getUserById(user.getId());
        if (userVO == null) {
            log.warn("获取用户信息失败，用户ID：{}", user.getId());
            throw new RuntimeException("获取用户信息失败");
        }

        // 构建用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userVO.getId());
        userInfo.setUsername(userVO.getUsername());
        userInfo.setRealName(userVO.getRealName());
        userInfo.setEmail(userVO.getEmail());
        userInfo.setPhone(userVO.getPhone());
        userInfo.setAvatar(userVO.getAvatar());
        
        // 设置角色信息
        List<String> roleNames = userVO.getRoles().stream()
                .map(RoleVO::getRoleName)
                .collect(Collectors.toList());
        userInfo.setRoles(roleNames);

        // 生成JWT Token
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userVO.getId());
        claims.put("username", userVO.getUsername());
        claims.put("realName", userVO.getRealName());
        claims.put("roles", roleNames);
        String token = jwtUtils.generateToken(claims);

        log.info("用户登录成功，用户ID：{}，用户名：{}", userVO.getId(), userVO.getUsername());
        return new LoginResponse(token, userInfo);
    }

    @Override
    public UserInfo getUserInfo(Long userId) {
        log.info("获取用户信息，用户ID：{}", userId);

        if (userId == null) {
            log.warn("用户ID不能为空");
            throw new RuntimeException("用户ID不能为空");
        }

        // 从数据库获取用户信息
        UserVO userVO = userService.getUserById(userId);
        if (userVO == null) {
            log.warn("用户不存在，用户ID：{}", userId);
            throw new RuntimeException("用户不存在");
        }

        // 构建用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userVO.getId());
        userInfo.setUsername(userVO.getUsername());
        userInfo.setRealName(userVO.getRealName());
        userInfo.setEmail(userVO.getEmail());
        userInfo.setPhone(userVO.getPhone());
        userInfo.setAvatar(userVO.getAvatar());
        
        // 设置角色信息
        List<String> roleNames = userVO.getRoles().stream()
                .map(RoleVO::getRoleName)
                .collect(Collectors.toList());
        userInfo.setRoles(roleNames);

        log.info("获取用户信息成功，用户ID：{}", userId);
        return userInfo;
    }
}